package com.cloud.controller;

import com.cloud.constant.DatabaseConstant;
import com.cloud.model.system.SysRole;
import com.cloud.model.system.SysUser;
import com.cloud.service.SysRoleService;
import com.cloud.service.SysUserService;
import com.cloud.utils.PasswordHelper;
import com.cloud.utils.Result;
import com.cloud.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2017/3/16.
 */
@RestController
public class SysUserController {
    private Logger logger = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private PasswordHelper passwordHelper;

    /**
     * 带分页查询
     *
     * @param sysUser
     * @param page
     * @param size
     * @return
     */
    @GetMapping(value = "users")
    //@RequiresPermissions("users:select")
    public Page<SysUser> queryAll(SysUser sysUser,
                                  @RequestParam(value = "page", defaultValue = "0") Integer page,
                                  @RequestParam(value = "size", defaultValue = "10") Integer size) {
        return sysUserService.findAll(sysUser, page, size);
    }

    /**
     * 删除用户
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "users/{ids}")
    public Result<SysUser> deletUser(@PathVariable String ids) {
        try {
            String[] idArrayList = ids.split(",");
            List<SysUser> list = new ArrayList<SysUser>();
            for (int i = 0; i < idArrayList.length; i++) {
                SysUser sysUser = new SysUser();
                sysUser.setId(Long.valueOf(idArrayList[i]));
                list.add(sysUser);
            }
            sysUserService.delete(list);
            logger.info("删除用户={}", ids);
            return ResultUtils.success("删除成功");
        } catch (NumberFormatException e) {
            logger.error("删除用户失败=={}", e.getMessage());
            return ResultUtils.error("删除失败");
        }

    }

    /**
     * 更改用户
     *
     * @param sysUser
     * @param roleIds
     * @return
     */
    @PutMapping(value = "users")
    public Result<SysUser> updateUser(@Valid SysUser sysUser, String roleIds,BindingResult result) {
        if (result.hasErrors()){
            return ResultUtils.error(result.getFieldError().getDefaultMessage());
        }
        //如果密码为空的话，说明用户没有修改密码，需要从数据库中查询出来
        if (StringUtils.isBlank(sysUser.getUserPassword())) {
            sysUser = sysUserService.findOne(sysUser.getId());
        } else {
            passwordHelper.encryptPassword(sysUser);
        }
        if (StringUtils.isNotBlank(roleIds)) {
            //获取角色的id
            String[] roleIdArray = roleIds.split(",");
            List<Long> roleIdsList = new ArrayList<>();
            for (int i = 0; i < roleIdArray.length; i++) {
                roleIdsList.add(Long.valueOf(roleIdArray[i]));
            }
            List<SysRole> roleList = sysRoleService.findAll(roleIdsList);
            if (roleList.size()==0){
                return ResultUtils.error("修改用户失败，角色不存在！");
            }
            Set<SysRole> sysRoles = new HashSet<>(roleList);
            sysUser.setRoles(sysRoles);
        }
        try {
            sysUserService.saveUser(sysUser);
            logger.info("编辑用户={}", sysUser.getUserName());
            return ResultUtils.success("修改成功", sysUser);
        } catch (Exception e) {
            logger.error("编辑用户失败={}", e.getMessage());
            return ResultUtils.error("修改失败");
        }
    }

    /**
     * 添加用户
     *
     * @param
     * @return
     */
    @PostMapping(value = "users")
    public Result<SysUser> addUser(@Valid SysUser sysUser, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtils.error(result.getFieldError().getDefaultMessage());
        }
        try {
            passwordHelper.encryptPassword(sysUser);
            sysUser.setUserAvailable(DatabaseConstant.USE_ABLE);
            sysUser = sysUserService.saveUser(sysUser);
            logger.info("添加用户=={}", sysUser.getUserName());
            return ResultUtils.success("添加用户成功", sysUser);
        } catch (Exception e) {
            logger.error("添加用户失败={}", e.getMessage());
            return ResultUtils.error("添加用户失败");
        }
    }

    /**
     * 改变用户状态
     *
     * @param
     * @return
     */
    @PutMapping(value = "users/{id}/status")
    public Result<SysUser> changeStatus(SysUser sysUser) {
        sysUser = sysUserService.findOne(sysUser.getId());
        try {
            if (sysUser.getUserAvailable() == DatabaseConstant.USER_UNABLE) {
                sysUser.setUserAvailable(DatabaseConstant.USE_ABLE);
                sysUserService.saveUser(sysUser);
                return ResultUtils.success("启用用户成功", sysUser);
            } else {
                sysUser.setUserAvailable(DatabaseConstant.USER_UNABLE);
                sysUserService.saveUser(sysUser);
                return ResultUtils.success("用户｛" + sysUser.getUserName() + "｝已锁定", sysUser);
            }
        } catch (Exception e) {
            logger.error("改变用户装填失败={}", e.getMessage());
            return ResultUtils.error("网络异常，操作失败");
        }
    }

    @PutMapping(value = "users/{id}/pwd")
    public Result<SysUser> editPwd(@PathVariable Long id, @RequestParam("oldPwd") String oldPwd, @RequestParam("newPwd") String newPwd) {
        SysUser sysUser = sysUserService.findOne(id);
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(), oldPwd);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
        } catch (AuthenticationException e) {
            logger.error(sysUser.getUserName() + "输入密码：{}与原始密码不匹配", newPwd);
            return ResultUtils.error("修改失败，原始密码输入不正确");
        }
        try {
            sysUser.setUserPassword(newPwd);
            passwordHelper.encryptPassword(sysUser);
            sysUserService.saveUser(sysUser);
            return ResultUtils.success("修改密码成功，请牢记您的新密码！");
        } catch (AuthenticationException e) {
            logger.error("修改密码失败=={}", e.getMessage());
            return ResultUtils.error("修改密码失败，请与管理员联系");
        }
    }
}

